<template>
    <!--地图挂载dom-->
    <div id="map">
        <div id="info">&nbsp;</div>
    </div>
</template>

<script>
    //引入依赖
    import KML from 'ol/format/KML';
    import Map from 'ol/Map';
    import VectorSource from 'ol/source/Vector';
    import View from 'ol/View';
    import XYZ from 'ol/source/XYZ';
    import OSM from 'ol/source/OSM'
    import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
    export default {
        name: 'KmlLayer',
        data() {
            return {
            }
        },
        mounted() {

            const raster = new TileLayer({
                source: new OSM()//加载OpenStreetMap
            });
            //kml是矢量数据，需要使用矢量数据源加载，然后使用矢量图层渲染
            const vector = new VectorLayer({
                source: new VectorSource({
                    url: 'http://localhost:8888/openlayer/kml/2012-02-10.kml',
                    format: new KML(),//必须使用kml格式加载
                }),
            });
            //渲染矢量图层
            const map = new Map({
                layers: [raster, vector],
                target: document.getElementById('map'),
                view: new View({
                    center: [876970.8463461736, 5859807.853963373],
                    projection: 'EPSG:3857',
                    zoom: 10,
                }),
            });

            const displayFeatureInfo = function (pixel) {
                const features = [];
                //遍历地图当前像素下的所有的矢量要素数据
                map.forEachFeatureAtPixel(pixel, function (feature) {
                    features.push(feature);
                });
                if (features.length > 0) {
                    const info = [];
                    let i, ii;
                    //通过name属性获取到要素的值
                    for (i = 0, ii = features.length; i < ii; ++i) {
                        info.push(features[i].get('name'));
                    }
                    //将要素的name值放到info框
                    document.getElementById('info').innerHTML = info.join(', ') || '(unknown)';
                    //鼠标放在地图map上的鼠标样式：手型
                    map.getTarget().style.cursor = 'pointer';
                } else {
                    document.getElementById('info').innerHTML = '&nbsp;';
                    map.getTarget().style.cursor = '';
                }
            };
            //地图的鼠标移动事件
            map.on('pointermove', function (evt) {
                if (evt.dragging) {
                    return;
                }
                //获取到鼠标移动的像素信息
                const pixel = map.getEventPixel(evt.originalEvent);
                displayFeatureInfo(pixel);
            });
            //地图的鼠标点击事件
            map.on('click', function (evt) {
                //获取到鼠标点击的像素信息
                displayFeatureInfo(evt.pixel);
            });
        },
        methods: {
        }
    }
</script>

<style scoped>

    #info {
        position: absolute;
        top: .5em;
        right: .5em;
        z-index: 9999;
    }
</style>